package com.lingyun.ucm.web.mvc.service.impl.configfile.impl;

import com.alibaba.fastjson.JSON;
import com.lingyun.ucm.common.exception.UtilException;
import com.lingyun.ucm.common.pojo.bean.ConfigStoreValue;
import com.lingyun.ucm.common.zk.ZkClientUtil;

import org.I0Itec.zkclient.ZkClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Properties;

/**
 * 
 * @author Terrence2013
 * 2018年1月24日 上午9:54:52
 * properties文件配置初始化对象
 */
public class PropertiesProcessor extends AbsConfigFileProcessor {
    @Override
    public void importConfig(InputStream in, ZkClient zkClient) throws IOException, UtilException {
        Properties properties = new Properties();
        properties.load(new InputStreamReader(in, "UTF-8"));
        Iterator<String> names = properties.stringPropertyNames().iterator();
        while (names.hasNext()) {
            String configKey = names.next();
            String path = ZkClientUtil.getPathFromClientKey(configKey);
            ZkClientUtil.checkPath(path);
            if (!zkClient.exists(path)) {
                zkClient.createPersistent(path, true);
            }
            String storeValue;
            String configValue = properties.getProperty(configKey);
            //配置项的值的合法格式为json或直接value:{\"canEdit\":\"true\",\"canDel\":\"true\",\"value\":\"xxxxx\"} 或 xxxxx;
            if (configValue.contains("canEdit") && configValue.contains("canDel") && configValue.contains("value")) {
                storeValue = configValue;
            } else {
                storeValue = JSON.toJSONString(new ConfigStoreValue(true, true, configValue));
            }
            zkClient.writeData(path, storeValue);
        }
    }
}
